package com.dlx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlx.acl.client.UserFeignClient;
import com.dlx.activity.client.RechargeActivityFeignClient;
import com.dlx.common.exception.SmmsException;
import com.dlx.common.result.Result;
import com.dlx.enums.RechargeOrderStatusEnum;
import com.dlx.mem.client.MemInfoFeignClient;
import com.dlx.mem.client.MemLevelFeignClient;
import com.dlx.model.acl.User;
import com.dlx.model.activity.RechargeActivity;
import com.dlx.model.mem.MemInfo;
import com.dlx.model.mem.MemLevel;
import com.dlx.model.order.RechargeOrderInfo;
import com.dlx.order.mapper.RechargeOrderInfoMapper;
import com.dlx.order.service.RechargeOrderInfoService;
import com.dlx.vo.order.RechargeOrderInfoQueryVo;
import com.dlx.vo.order.RechargeOrderReportQueryVo;
import com.dlx.vo.order.RechargeOrderReportVo;
import com.dlx.vo.order.RechargeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author nglon
 * @since 2021-11-16
 */
@Service
public class RechargeOrderInfoServiceImpl extends ServiceImpl<RechargeOrderInfoMapper, RechargeOrderInfo> implements RechargeOrderInfoService {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private MemInfoFeignClient memInfoFeignClient;

    @Autowired
    private MemLevelFeignClient memLevelFeignClient;

    @Autowired
    private RechargeActivityFeignClient rechargeActivityFeignClient;

    @Override
    public Boolean recharge(RechargeVo rechargeVo) {
        User user = this.userFeignClient.getCurrentUser();
        if (!user.getPassword().equals(rechargeVo.getPaymentPassword())) {
            throw new SmmsException(332, "账号密码错误");
        }
        MemInfo memInfo = memInfoFeignClient.getById(rechargeVo.getMemInfoId());
        if (Objects.isNull(memInfo)) {
            throw new SmmsException(333, "无此会员编号");
        }
        memInfo.setBalance(memInfo.getBalance().add(rechargeVo.getRechargeAmount()));
        memInfo.setTotalRecharge(memInfo.getTotalRecharge().add(rechargeVo.getRechargeAmount()));
        // TODO 判断当前是否处于活动时间
        RechargeActivity rechargeActivity = this.rechargeActivityFeignClient.whetherInActivityTime(LocalDateTime.now());
        if(Objects.nonNull(rechargeActivity)){
            Integer divide = rechargeVo.getRechargeAmount().divide(rechargeActivity.getRechargeAmount()).setScale(0,RoundingMode.DOWN).intValue();
            memInfo.setPoints(rechargeActivity.getGiftPoints()*divide);
        }

        List<MemLevel> levelList = this.memLevelFeignClient.getLevelList();
        for (MemLevel memLevel : levelList) {
            if (memLevel.getLeftInterval() == null) {
                if(memInfo.getBalance().compareTo(memLevel.getRightInterval()) <= 0){
                    memInfo.setLevelId(memLevel.getId());
                }
            } else if (memLevel.getRightInterval() == null) {
                if(memInfo.getBalance().compareTo(memLevel.getLeftInterval()) > 0){
                    memInfo.setLevelId(memLevel.getId());
                }
            } else if (memInfo.getBalance().compareTo(memLevel.getLeftInterval()) > 0 && memInfo.getBalance().compareTo(memLevel.getLeftInterval()) <= 0) {
                memInfo.setLevelId(memLevel.getId());
            }
        }
        Result memInfoResult = memInfoFeignClient.update(memInfo);

        boolean flag = false;
        if (memInfoResult.getCode()==200) {
            RechargeOrderInfo rechargeOrderInfo = new RechargeOrderInfo();
            rechargeOrderInfo.setRechargerId(user.getId());
            rechargeOrderInfo.setRechargedId(rechargeVo.getMemInfoId());
            rechargeOrderInfo.setRechargeAmount(rechargeVo.getRechargeAmount());
            rechargeOrderInfo.setStatus(1);
            flag = baseMapper.insert(rechargeOrderInfo) > 0;
        }
        return flag;
    }

    @Override
    public Page<RechargeOrderInfo> selectRechargeOrderInfoPage(Long current, Long limit, RechargeOrderInfoQueryVo rechargeOrderInfoQueryVo) {
        QueryWrapper<RechargeOrderInfo> wrapper = new QueryWrapper<>();
        User user = this.userFeignClient.getCurrentUser();
        if (!"admin".equals(user.getUsername())) {
            wrapper.eq("recharger_id", user.getId()).or().eq("recharged_id",user.getId());
        }
        if(rechargeOrderInfoQueryVo.getId()!=null){
            wrapper.like("id",rechargeOrderInfoQueryVo.getId());
        }
        if(rechargeOrderInfoQueryVo.getRechargerId()!=null){
            wrapper.like("recharger_id",rechargeOrderInfoQueryVo.getRechargerId());
        }
        if(rechargeOrderInfoQueryVo.getRechargedId()!=null){
            wrapper.like("recharged_id",rechargeOrderInfoQueryVo.getRechargedId());
        }

        Page<RechargeOrderInfo> rechargeOrderInfoPage = this.baseMapper.selectPage(new Page<>(current, limit), wrapper);
        rechargeOrderInfoPage.getRecords().forEach(this::packageRechargeOrderInfo);
        return rechargeOrderInfoPage;
    }

    @Override
    public RechargeOrderInfo show(Long id) {
        RechargeOrderInfo rechargeOrderInfo = this.baseMapper.selectById(id);
        this.packageRechargeOrderInfo(rechargeOrderInfo);
        return rechargeOrderInfo;
    }

    @Override
    public Map<String, Object> getMonthlyReport(RechargeOrderReportQueryVo vo) {
        Map<String, Object> map = new HashMap<>();
        List<RechargeOrderReportVo> rechargeOrderMonthlyReportVoList = this.baseMapper.selectMonthlyReport(vo);
        List<String> xCoordinatesList = rechargeOrderMonthlyReportVoList.stream().map(RechargeOrderReportVo::getXCoordinates).collect(Collectors.toList());
        List<BigDecimal> yCoordinatesList = rechargeOrderMonthlyReportVoList.stream().map(RechargeOrderReportVo::getYCoordinates).collect(Collectors.toList());
        map.put("xCoordinatesList",xCoordinatesList);
        map.put("yCoordinatesList",yCoordinatesList);
        return map;
    }

    @Override
    public Map<String, Object> getQuarterlyReport(RechargeOrderReportQueryVo vo) {
        Map<String, Object> map = new HashMap<>();
        List<RechargeOrderReportVo> rechargeOrderMonthlyReportVoList = this.baseMapper.selectQuarterlyReport(vo);
        List<String> xCoordinatesList = rechargeOrderMonthlyReportVoList.stream().map(RechargeOrderReportVo::getXCoordinates).collect(Collectors.toList());
        List<BigDecimal> yCoordinatesList = rechargeOrderMonthlyReportVoList.stream().map(RechargeOrderReportVo::getYCoordinates).collect(Collectors.toList());
        map.put("xCoordinatesList",xCoordinatesList);
        map.put("yCoordinatesList",yCoordinatesList);
        return map;
    }

    @Override
    public Map<String, Object> getAnnualReport() {
        Map<String, Object> map = new HashMap<>();
        List<RechargeOrderReportVo> rechargeOrderMonthlyReportVoList = this.baseMapper.selectAnnualReport();
        List<String> xCoordinatesList = rechargeOrderMonthlyReportVoList.stream().map(RechargeOrderReportVo::getXCoordinates).collect(Collectors.toList());
        List<BigDecimal> yCoordinatesList = rechargeOrderMonthlyReportVoList.stream().map(RechargeOrderReportVo::getYCoordinates).collect(Collectors.toList());
        map.put("xCoordinatesList",xCoordinatesList);
        map.put("yCoordinatesList",yCoordinatesList);
        return map;
    }

    @Override
    public RechargeActivity getRechargeActivityInfo() {
        RechargeActivity rechargeActivity = this.rechargeActivityFeignClient.whetherInActivityTime(LocalDateTime.now());
        return rechargeActivity;
    }

    private void packageRechargeOrderInfo(RechargeOrderInfo rechargeOrderInfo) {
        User recharger = this.userFeignClient.getById(rechargeOrderInfo.getRechargerId());
        rechargeOrderInfo.getParam().put("rechargerUsername", StringUtils.hasText(recharger.getUsername())?recharger.getUsername():recharger.getEmail());
        MemInfo recharged = this.memInfoFeignClient.getById(rechargeOrderInfo.getRechargedId());
        rechargeOrderInfo.getParam().put("rechargedUsername",recharged.getNickname());
        String stringOrderStatus = RechargeOrderStatusEnum.getStatusNameByStatus(rechargeOrderInfo.getStatus());
        rechargeOrderInfo.getParam().put("stringOrderStatus",stringOrderStatus);
    }
}
